#!/alidata/server/php/bin/php
<?php
error_reporting(0);
ini_set('memory_limit', '1000M');
set_time_limit(0);

/**
 * 相同经纪公司房源去重
 * 输出字段：小区id \t 室 \t 厅 \t 楼层 \t 总楼层
 */

// type字典
// 当前数据
$currList = array();
// 上一个数据
$lastList = array();
// 同一个小区数据数组
$arrBorough = array();

while (($line_json = fgets(STDIN)) !== false) {
    $line_json = trim($line_json);
    if (empty($line_json))
        continue;
    list ($borough_id, $list_json_sell_gov) = explode("\t", $line_json);
    $currList['borough_id'] = $borough_id;
    $currList['list_json'] = $list_json_sell_gov;
	$list_dejson_curr = handle_json_decode($list_json_sell_gov);
    if ($currList['borough_id'] == $lastList['borough_id']) {  //同小区 
		$arrBorough['borough_id'] = $currList['borough_id'];    //原逻辑有误，第一条单小区数据将不被handle
        $arrBorough['data'][$list_dejson_curr['id']] = $list_dejson_curr;
        
    } else {
        
        if (! empty($lastList)) {
            if (! empty($arrBorough)) {
                // 处理房源合并
                handleHouse($arrBorough);
                $arrBorough = array();
            } 
        }
	$arrBorough=array();
	$arrBorough['borough_id'] = $currList['borough_id'];
    $arrBorough['data'][$list_dejson_curr['id']] = $list_dejson_curr;
    }
    
    $lastList = $currList;
}

if (! empty($arrBorough)) {
    handleHouse($arrBorough);
}elseif(!empty($lastList)){    //原逻辑有误，最后一条房源可能handle两次
        $arrBorough=array();
        $list_dejson = handle_json_decode($lastList['list_json']);
        $arrBorough['borough_id'] = $lastList['borough_id'];
        $arrBorough['data'][$list_dejson['id']] = $list_dejson;
        handleHouse($arrBorough);
}
function handleHouse($arrBorough = array())
{
    /**
     * 准入条件：
     * 1、总楼层相同 house_topfloor
     * 2、所在楼层相同 house_floor
     * 3、室相同 room
     * 4、总面积相差1平米 house_totalarea
     * 5、不是同一个经纪公司
     */
        // $arrBorough[$currList['borough_id']][$list_dejson['id']] = $list_dejson
    $borough_id = $arrBorough['borough_id'];
    $arrBoroughList = $arrBorough['data'];
    //如果是独立房源，直接输出
    if(count($arrBoroughList) == 1){
        //echo "独立房源！";
		foreach($arrBoroughList as $a)
			if (! empty($a))
			    echo json_encode($a)."\n";
        return;
    }
else{
    $arrTempBoroughList = $arrBoroughList;
	$flag_com=array();   //是否对比上的标识
	//初始化为全0 
	foreach ($arrBoroughList as $key => $value){
		if($value['house_floor']==""||$value['house_floor']=='0'||$value['house_floor']==null){
			$flag_com[$key]=1;
			$value['weight']=0;
			echo json_encode($value)."\n";
		}
		else	$flag_com[$key]=0;
	}
    $group_id = 0;
	foreach ($arrBoroughList as $key => $value){

		if($flag_com[$key]==1) continue;
        $source=$value['source'];
        if (strlen($source) == 1){
            $source="0".$source;
        }
        echo $borough_id.":".$group_id.".".$source."\t".json_encode($value)."\n";
        $flag_com[$key]=1;
        
		foreach($arrTempBoroughList as $tmpKey => $tmpValue){
			if($flag_com[$tmpKey]==1) continue;  //already grouped
			if($key==$tmpKey)  continue;  //same one

			if (!isAccess($value, $tmpValue)) {
    			continue;  //准入条件不符合要求
            }
            $source=$tmpValue['source'];
            if (strlen($source) ==1){
                $source="0".$source;
            }
            echo $borough_id.":".$group_id.".".$source."\t".json_encode($tmpValue)."\n";
            $flag_com[$tmpKey]=1;
        }
        $group_id = $group_id + 1;
	}
    #$group_id = $group_id + 1;
}
}

//准入条件
function isAccess($value, $tmpValue){
    return  (isEqualFloor($value, $tmpValue) && isEqualRoom($value, $tmpValue) 
                && isEqualTopFloor($value, $tmpValue) 
                && isEqualTotalArea($value, $tmpValue));
}
//判断总楼层是否相同
function isEqualTopFloor($value, $tmpValue)
{
    if (($value['house_topfloor'] == 0) || ($tmpValue['house_topfloor'] == 0)){
        return True;
    }
    $flag = $value['house_topfloor'] == $tmpValue['house_topfloor'];
    
    return $flag;
}
//判断所在楼层是否相同
function isEqualFloor($value, $tmpValue)
{
	$numeric_floor_min = "";
    $numeric_floor_max = "";
    $string_floor = "";
    if (is_numeric($value['house_floor'])) {//如果是数字，则匹配具体楼层数字和模糊匹配高中低
        $house_floor = $value['house_floor'];
        if ($value['house_floor'] < ($value['house_topfloor'] / 3)) {
            $string_floor = "低";
        } elseif ($value['house_floor'] >= ($value['house_topfloor'] / 3) && $value['house_floor'] <= ($value['house_topfloor'] * (2 / 3))) {
            $string_floor = "中";
        } else {
            $string_floor = "高";
        }
        $numeric_floor_min =  $value['house_floor'];
        $numeric_floor_max =  $value['house_floor'];
    } else {//如果是汉字（高中低），匹配高中低并且范围匹配数字
        $grep_value_floor = "";
        preg_match("/(中|高|低", $value['house_floor'], $grep_value_floor);
        if (! empty($grep_value_floor) && ! empty($grep_value_floor[1])) {
            $value['house_floor'] = $grep_value_floor[1];
        }
        
        $grep_tmp_value_floor = "";
      //  preg_match("/(中|高|低).*/", $tmpValue['house_floor'], $grep_tmp_value_floor);
      //  if (! empty($grep_tmp_value_floor) && ! empty($grep_tmp_value_floor[1])) {
      //      $tmpValue['house_floor'] = $grep_tmp_value_floor[1];
      //  }
        
        // 如果是汉字换算成数字
        if ($value['house_floor'] == "低") {
            $numeric_floor_min = - 1;
            $numeric_floor_max = ($value['house_topfloor'] / 3);
        } elseif ($value['house_floor'] == '中') {
            $numeric_floor_min = ($value['house_topfloor'] / 3);
            $numeric_floor_max = ($value['house_topfloor'] * (2 / 3));
        } elseif ($value['house_floor'] == '高') {
            $numeric_floor_min = ($value['house_topfloor'] * (2 / 3));
            $numeric_floor_max = $value['house_topfloor'];
        } else {
            $numeric_floor_min = - 999;
            $numeric_floor_max = - 99;
        }
    }
	if($value['house_floor']=="低" &&is_numeric($tmpValue['house_floor'])==false){
		if($tmpValue['house_floor']=="低")  return true;
		else{
            return false;
        }
	} 
    elseif (($value['house_floor'] == $tmpValue['house_floor']) || ($string_floor == $tmpValue['house_floor']) || ($tmpValue['house_floor'] >= $numeric_floor_min && $tmpValue['house_floor'] <= $numeric_floor_max)) 
    {
        //echo "相同\n";
        return true;
    }else{
        //echo "不相同\n";
        return false;
    }
}
//判断室是否相同
function isEqualRoom($value, $tmpValue)
{
    $flag = $value['house_room'] == $tmpValue['house_room'];
    return $flag;
}
    // 判断总面积是否相似
function isEqualTotalArea($value, $tmpValue)
{
    $flag = ($value['house_totalarea'] >= $tmpValue['house_totalarea'] - 1) && ($value['house_totalarea'] <= $tmpValue['house_totalarea'] + 1);
    return $flag;
}

//去重，字符串前、中、后
function trimall($value){
    $before=array(" ","　","\t","\n","\r");
    $after=array("","","","","");
    return str_replace($before,$after,$value);
}
//json_decode,数组中所有的value都进行trimall操作
function handle_json_decode($line_json){
    $line_json_tmp=json_decode($line_json, true);
    if(!is_array($line_json_tmp) || empty($line_json_tmp)){
        return array();
    }else{
        foreach($line_json_tmp as $key=>$value){
            $line_json_tmp[$key]=trimall($value);
        }
        return $line_json_tmp;
    }
}

?>
